<template>
  <div class="edu-page-warp">
    <examination-search @reset="reset" @onSubmit="setQueryForm"></examination-search>
    <el-card>
      <div class="edu-page-title" style="margin-bottom:24px;">{{$t('examinationList.list')}}</div>
      <div class="edu-opertion-bar" style="margin-bottom:16px;">
        <div class="float-left">
          <el-input
            v-model="queryForm.condition"
            :placeholder="$t('examinationList.codition')"
            style="width:200px"
            @keyup.enter.native="onSubmit"
          >
            <i
              class="el-icon-search"
              slot="suffix"
              style="margin-top:10px;cursor:pointer"
              @click="onSubmit"
            ></i>
          </el-input>
        </div>
        <div class="float-right">
          <el-button @click="exportList">{{$t("message.export")}}</el-button>
          <el-button @click="downListTemplate">{{$t("exam.impotTemplate")}}</el-button>
          <el-button @click="importExcel">{{$t("message.import")}}</el-button>
          <el-button @click="addExamStudents" type="primary">{{$t('message.add')}}</el-button>
        </div>
      </div>
      <edu-table
        :url="api.pageUrl"
        ref="examinationLevelTable"
        size="mini"
        :order="false"
        @selection-change="chooseList"
      >
        <el-table-column :label="$t('examinationLevel.studentId')">
          <template slot-scope="scope">{{scope.row.studentId}}</template>
        </el-table-column>
        <el-table-column :label="$t('examinationLevel.name')">
          <template slot-scope="scope">{{scope.row.studentName}}</template>
        </el-table-column>
        <el-table-column :label="$t('nonPublicCourseOpen.grade')">
          <template slot-scope="scope">{{scope.row.grade}}</template>
        </el-table-column>
        <el-table-column :label="$t('nonPublicCourseOpen.college')" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.facultyI18n}}</template>
        </el-table-column>
        <el-table-column :label="$t('nonPublicCourseOpen.major')" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.majorI18n}}</template>
        </el-table-column>
        <el-table-column :label="$t('examinationLevel.subject')">
          <template slot-scope="scope">{{scope.row.subjectI18n}}</template>
        </el-table-column>
        <el-table-column :label="$t('examinationLevel.examTime')" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.examTime}}</template>
        </el-table-column>
        <el-table-column :label="$t('message.remark')" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.remark}}</template>
        </el-table-column>
        <el-table-column :label="$t('exam.notice')" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.notice}}</template>
        </el-table-column>
        <el-table-column :label="$t('examinationLevel.examAddress')" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.examAddress}}</template>
        </el-table-column>
        <el-table-column :label="$t('message.operating')">
          <template slot-scope="scope">
            <el-button v-if="scope.row.examFlag != 0"
              type="text"
              @click="editById(scope.row.id)"
              size="mini"
            >{{$t('message.edit')}}</el-button>
            <el-button v-if="scope.row.examFlag != 0"
              type="text"
              @click="deleteById([scope.row.id])"
              size="mini"
            >{{$t('message.delete')}}</el-button>
          </template>
        </el-table-column>
      </edu-table>
    </el-card>
    <edu-dialog
      :title="dialogTitle"
      width="700px"
      :visible.sync="showDeptsDialog"
      @close="resetAddForm"
      @confirm="submitForm"
    >
      <el-form
        :model="createForm"
        ref="createForm"
        label-width="85px"
        :rules="rules"
        class="createForm"
        label-position="right"
      >
        <el-row>
          <el-col :span="11">
            <el-form-item prop="calendarId" :label="$t('label.schoolTerm')">
              <CalendarSelect v-model="createForm.calendarId"></CalendarSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="subject" :label="$t('examinationLevel.subject')">
              <el-select v-model="createForm.subject">
                <el-option
                  v-for="item in options.subjects"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item prop="studentId" :label="$t('examinationLevel.studentId')">
              <el-input v-model="createForm.studentId" @change="studentIdChange" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('examinationLevel.name')">
              <el-input
                v-model="createForm.studentName"
                :placeholder="$t('exam.autoGet')"
                readonly="true"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item :label="$t('nonPublicCourseOpen.grade')">
              <el-input
                v-model="createForm.grade"
                :placeholder="$t('exam.autoGet')"
                readonly="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('nonPublicCourseOpen.college')">
              <el-input
                v-model="createForm.facultyI18n"
                :placeholder="$t('exam.autoGet')"
                readonly="true"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item :label="$t('nonPublicCourseOpen.major')">
              <el-input
                v-model="createForm.majorI18n"
                :placeholder="$t('exam.autoGet')"
                readonly="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="isExam" :label="$t('examinationLevel.isExam')">
              <el-select v-model="createForm.isExam" @change="changeIsExam">
                <el-option
                  v-for="item in options.isExams"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item prop="beginTime" :label="$t('examinationLevel.examTime')">
              <el-date-picker
                v-model="createForm.beginTime"
                type="datetime"
                :placeholder="$t('examinationLevel.inputBegin')"
                value-format="timestamp"
                format="yyyy/MM/dd HH:mm"
                :disabled="examReadOnly"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="createForm.endTime"
                type="datetime"
                :placeholder="$t('examinationLevel.inputEnd')"
                value-format="timestamp"
                format="yyyy/MM/dd HH:mm"
                :disabled="examReadOnly"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item prop="examAddress" :label="$t('examinationLevel.examAddress')">
              <el-input
                v-model="createForm.examAddress"
                :placeholder="$t('exam.plsInput')"
                :disabled="examReadOnly"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="23">
            <!-- class="auto-height" -->
            <el-form-item :label="$t('message.remark')">
              <el-input type="textarea" v-model="createForm.remark" maxlength="200"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <el-form-item :label="$t('exam.notice')">
              <el-input type="textarea" v-model="createForm.notice" maxlength="200"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </edu-dialog>
    <edu-dialog
      :title="$t('exam.listImport')"
      width="500px"
      ref="uploadDialog"
      @close="clearFiles"
      @confirm="uploadFile"
    >
      <el-form label-width="85px" v-loading="loading1">
        <el-row>
          <el-form-item>
            <el-upload
              ref="upload"
              :data="{}"
              :on-success="uploadDone"
              :on-error="onError"
              :auto-upload="false"
              :multiple="false"
              :on-change="(file, fileList)=>{this.fileList = fileList}"
              :limit="1"
              :accept="'application/vnd.ms-excel'"
              action="api/welcomeservice/examinationStudents/import/examList"
            >
              <el-button slot="trigger" size="small" type="primary">{{$t('label.selectFile')}}</el-button>
              <div slot="tip" class="el-upload__tip">{{$t('courseTake.uploadXLSFileOnly')}}</div>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>
    </edu-dialog>
  </div>
</template>

<script>
import ExaminationSearch from "./components/ExaminationSearch";
import examinationStudentsApi from "common/src/api/welcomeService/examinationStudents";
import UTILS from "common/src/utils/utils";
import { queryDic } from "common/src/api/dictionary";

export default {
  name: "ExaminationList",
  components: { ExaminationSearch },
  data() {
    return {
      api: examinationStudentsApi,
      isEdit: false,
      showDeptsDialog: false,
      //当前登录用户部门
      curColleges:[],
      options: {
        isExams: [],
        subjects: [],
        calendarId: []
      },
      queryForm: {
        condition: "",
        calendarId: null,
        subject: "",
        grade: "",
        faculty: "",
        major: "",
        isExam: ""
      },
      createForm: {
        id: "",
        calendarId: "",
        subject: "",
        studentId: "",
        studentName: "",
        grade: "",
        faculty: "",
        facultyI18n: "",
        major: "",
        majorI18n: "",
        isExam: "",
        beginTime: "",
        endTime: "",
        examTime: "",
        remark: "",
        notice: "",
        examAddress: ""
      },
      chooseLists: [],
      examReadOnly: true,
      rules: {
        calendarId: [
          {
            required: true,
            message: this.$t("message.inputRequired"),
            trigger: "change"
          }
        ],
        studentId: [
          {
            required: true,
            validator: this.checkStudentId,
            trigger: "blur"
          }
        ],
        subject: [
          {
            required: true,
            message: this.$t("message.inputRequired"),
            trigger: "change"
          }
        ],
        isExam: [
          {
            required: true,
            message: this.$t("message.inputRequired"),
            trigger: "change"
          }
        ],
        beginTime: [
          {
            validator: this.checkBeginTime,
            trigger: "change",
            required: true
          }
        ],
        endTime: [
          {
            validator: this.checkEndTime,
            trigger: "change",
            required: true
          }
        ],
        examAddress: [
          {
            required: true,
            validator: this.checkAddress,
            trigger: "change"
          }
        ]
      },
      loading1:false
    };
  },
  mounted() {
    this.init();
  },
  watch: {
    createForm: {
      handler(curVal, oldVal) {
        if ("0" == curVal.isExam) {
          this.examReadOnly = true;
          this.createForm.beginTime = "";
          this.createForm.endTime = "";
          this.createForm.examTime = "";
          this.createForm.examAddress = "";
        } else if ("1" == curVal.isExam) {
          this.examReadOnly = false;
        }
      },
      deep: true
    }
  },
  methods: {
    init() {
      let yes = { label: this.$t("message.yes"), value: "1" };
      let no = { label: this.$t("message.no"), value: "0" };
      this.options.isExams.push(yes);
      this.options.isExams.push(no);
      //筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_KCKM"]
      };
      queryDic(data).then(res => {
        if (res.code == 200) {
          UTILS.fillSelect(
            {
              subjects: "X_KCKM"
            },
            res.data,
            this.options
          );
        }
      });
      //this.onSubmit();
      this.getColleges();
    },
    setQueryForm(data) {
      this.queryForm.calendarId = data.calendarId;
      this.queryForm.subject = data.subject;
      this.queryForm.grade = data.grade;
      this.queryForm.faculty = data.faculty;
      this.queryForm.major = data.major;
      this.queryForm.isExam = data.isExam;
      this.onSubmit();
    },
    exportList() {
      let loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, .48)"
      });
      let data = _.cloneDeep(this.queryForm);
      data.ids = this.chooseLists.map(c => c.id);
      examinationStudentsApi.exportList(data).then(res => {
        if (res.code == 200) {
          this.delayRequest(res.data.key, loading);
        } else {
          loading.close();
        }
      });
    },
    async delayRequest(key, loading) {
      await new Promise(resolve => setTimeout(resolve, 5000));
      examinationStudentsApi
        .getReportStatus(key)
        .then(res => {
          if (res.code == 200 && res.data.status) {
            let path = this.api.exportUrl + res.data.path;
            //window.open(path);
            window.location.href = path;
            loading.close();
          } else {
            this.delayRequest(key, loading);
          }
        })
        .catch(ex => {
          this.delayRequest(key, loading);
        });
    },
    chooseList(val) {
      this.chooseLists = val;
    },
    downListTemplate(fileName) {
      window.location.href = examinationStudentsApi.getListTempalte();
    },
    importExcel() {
      this.$refs.uploadDialog.open();
    },
    clearFiles() {
      this.$refs.upload.clearFiles();
      this.fileList = [];
    },
    uploadFile() {
      this.$refs.upload.submit();
    },
    uploadDone(res, file, fileList) {
      if (res.code == 200) {
      this.loading1 = true;
      this.delayImportRequest(res.data.key);
      } else {
        this.$message({
          type: "error",
          message: this.$t("common.tips.dataFormatError")
      });
        this.clearFiles();
      }
    },
     delayImportRequest(key) {
      setTimeout(() => {
      //await new Promise(resolve => setTimeout(resolve, 5000));
      examinationStudentsApi
        .getimportStatus(key)
        .then(res => {
          if (res.code == 200 && res.data.status) {
             this.loading1 = false;
            this.clearFiles();
            if(res.data.success){
              this.$message({
                type: "success",
                message: this.$t("common.tips.uploadSuccess")
              });
              this.$refs.uploadDialog.close();
              this.onSubmit();
            }else{
              this.$message({
              type: "error",
              message: res.data.msg
            });
            }

          } else {
            this.delayImportRequest(key);
          }
        })
        .catch(ex => {
          this.delayImportRequest(key);
        });
        }, 5000);
    },
    onError(err, file, fileList) {
      let msg = JSON.parse(err.message);
      this.$message({
        type: "error",
        message: msg.message
      });
    },
    // formatTime(value, type) {
    //   if (UTILS.isEmpty(value)) {
    //     return value;
    //   }
    //   let pat = "YYYY/MM/DD HH:mm";
    //   if ("d" == type) {
    //     pat = "YYYY/MM/DD";
    //   }
    //   return moment(value).format(pat);
    // },
    checkStudentId(rule, value, callback) {
      if (!value) {
        callback(new Error(this.$t("message.inputRequired")));
      } else if (!this.createForm.studentName) {
        callback(new Error(this.$t("exam.noStudent")));
      } else {
        callback();
      }
    },
    checkAddress(rule, value, callback) {
      if ("1" == this.createForm.isExam && !value) {
        callback(new Error(this.$t("message.inputRequired")));
      } else {
        callback();
      }
    },
    checkBeginTime(rule, value, callback) {
      if ("1" == this.createForm.isExam && !value) {
        callback(new Error(this.$t("message.inputRequired")));
      } else {
        callback();
      }
    },
    checkEndTime(rule, value, callback) {
      if ("1" == this.createForm.isExam && !value) {
        callback(new Error(this.$t("message.inputRequired")));
      } else if (
        this.createForm.beginTime &&
        this.createForm.beginTime >= this.createForm.endTime
      ) {
        callback(new Error(this.$t("examinationLevel.timeError")));
      } else {
        let begin = _.cloneDeep(this.createForm.beginTime);
        let end = _.cloneDeep(this.createForm.endTime);
        begin = this.formatTime(begin);
        end = this.formatTime(end);
        if (begin != end) {
          callback(new Error(this.$t("examinationLevel.timeEq")));
        } else {
          callback();
        }
      }
    },
    formatTime(value) {
      if (UTILS.isEmpty(value)) {
        return value;
      }
      return moment(value).format("YYYY/MM/DD");
    },
    onSubmit() {
      this.$refs.examinationLevelTable.search(this.queryForm);
    },
    deleteById(id) {
      let result = null;
      examinationStudentsApi.findById(id).then(res => {
        if (res.code == 200) {
          result = res.data.examResults;
          let error = "";
          if (!result) {
            error = this.$t("message.deleteConfirm");
          } else {
            error = this.$t("exam.error");
          }
          this.$confirm(error, this.$t("message.prompt"), {
            confirmButtonText: this.$t("message.confirm"),
            cancelButtonText: this.$t("message.cancel"),
            type: "warning"
          }).then(() => {
            examinationStudentsApi.deleteById(id).then(res => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: this.$t("message.deleteSuccess")
                });
                this.onSubmit();
              }
            });
          });
        }
      });
    },
    reset() {
      this.queryForm.condition = "";
    },
    editById(id) {
      this.isEdit = true;
      examinationStudentsApi.findById(id).then(res => {
        if (res.code == 200) {
          Object.keys(res.data).forEach(k => {
            if (this.createForm.hasOwnProperty(k)) {
              this.createForm[k] =
                res.data[k] == 0 || res.data[k] == 1
                  ? res.data[k].toString()
                  : res.data[k];
            }
            //'2019/05/07 00:00—02:00'
            if (this.createForm.examTime) {
              let times = this.createForm.examTime.split("-");
              let begin = times[0];
              console.info(times[1]);
              let timeEnd = times[0].split(" ");
              let end = timeEnd[0] + " " + times[1];
              console.info(end);
              this.createForm.beginTime = moment(
                begin,
                "YYYY/MM/DD HH:mm"
              ).toDate();
              this.createForm.endTime = moment(
                end,
                "YYYY/MM/DD HH:mm"
              ).toDate();
            }
          });
          this.showDialog = true;
        }
      });
      this.dialogTitle = this.$t("message.edit");
      this.showDeptsDialog = true;
    },
    addExamStudents() {
      this.isEdit = false;
      this.createForm.id = "";
      this.dialogTitle = this.$t("message.add");
      this.showDeptsDialog = true;
    },
    resetAddForm() {
      this.createForm.id = "";
      this.createForm.calendarId = "";
      this.createForm.subject = "";
      this.createForm.studentId = "";
      this.createForm.studentName = "";
      this.createForm.grade = "";
      this.createForm.faculty = "";
      this.createForm.facultyI18n = "";
      this.createForm.major = "";
      this.createForm.majorI18n = "";
      this.createForm.isExam = "";
      this.createForm.beginTime = "";
      this.createForm.endTime = "";
      this.createForm.examTime = "";
      this.createForm.remark = "";
      this.createForm.notice = "";
      this.createForm.examAddress = "";
      this.$refs.createForm.clearValidate();
    },
    submitForm() {
      this.$refs.createForm.validate(valid => {
        if (!valid) {
          return;
        }
        if (this.createForm.isExam == "1") {
          let begin = moment(this.createForm.beginTime).format(
            "YYYY/MM/DD HH:mm"
          );
          let end = moment(this.createForm.endTime).format("HH:mm");
          this.createForm.examTime = begin + "-" + end;
        } else {
          this.createForm.examTime = "";
        }
        if (this.createForm.id) {
          examinationStudentsApi.updateById(this.createForm).then(response => {
            if (response.code == 200) {
              this.showDialog = false;
              this.$message({
                type: "success",
                message: this.$t("message.saveSuccess")
              });
              this.createForm.id = "";
              this.showDeptsDialog = false;
              this.onSubmit();
            }
          });
        } else {
          examinationStudentsApi.save(this.createForm).then(response => {
            if (response.code == 200) {
              this.showDialog = false;
              this.$message({
                type: "success",
                message: this.$t("message.saveSuccess")
              });
              this.showDeptsDialog = false;
              this.onSubmit();
            }
          });
        }
      });
    },
    studentIdChange(val) {
      examinationStudentsApi.findByStudentId(val).then(res => {
        //  console.info("用户学院:"+res.data.faculty)
        //   console.info("登录用户学院:"+this.curColleges)
        if (res.code == 200 && res.data && (!this.curColleges || this.curColleges.includes(res.data.faculty))) {
          this.createForm.studentName = res.data.name;
          this.createForm.grade = res.data.grade;
          this.createForm.facultyI18n = res.data.facultyI18n;
          this.createForm.faculty = res.data.faculty;
          this.createForm.majorI18n = res.data.professionI18n;
          this.createForm.major = res.data.profession;
        } else {
          this.createForm.studentName = "";
          this.createForm.grade = "";
          this.createForm.facultyI18n = "";
          this.createForm.faculty = "";
          this.createForm.majorI18n = "";
          this.createForm.major = "";
        }
        this.$refs.createForm.validateField("studentId");
      });
    },
    changeIsExam() {
      this.$refs.createForm.clearValidate();
    },
    getColleges(){
      examinationStudentsApi.getColleges().then(res => {
        if(res.code == 200){
          this.curColleges = res.data
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.createForm {
  .line {
    text-align: center;
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
}
</style>
